import 'dart:async';

import 'package:flutter/material.dart';

class StreamBuilderDemoPage extends StatefulWidget {
  @override
  _StreamBuilderDemoPageState createState() => _StreamBuilderDemoPageState();
}

class _StreamBuilderDemoPageState extends State<StreamBuilderDemoPage> {
  final StreamController<String> _controller = StreamController.broadcast();

  Timer _timer;

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(Duration(seconds: 1), (t) {
      final d = DateTime.now();
      _controller.sink.add(DateTime(
              d.year, d.month, d.day, d.hour, d.minute, d.second)
          .toLocal()
          .toString());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("StreamBuilder Demo"),
      ),
      body: Center(
        child: StreamBuilder<String>(
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text("当前时间：${snapshot.data}");
            } else {
              return Container();
            }
          },
          stream: _controller.stream,
        ),
      ),
    );
  }

  @override
  void dispose() {
    if (_timer != null) {
      _timer.cancel();
    }
    _controller.close();
    super.dispose();
  }
}
